<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in CateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArticleList">筛选</el-button>
            <el-button type="info" size="small" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubDialogVisible = true">发表文章</el-button>
      </div>
      <!-- 文章表格区域 -->
      <el-table :data="ArticleList" style="width: 100%;" border stripe>
        <el-table-column label="文章标题" prop="title">
          <template v-slot="{row}">
            <el-link type="primary" @click="showDetail(row.id)">
              {{row.title}}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间" prop="pub_date">
          <template v-slot="{ row }">
            {{ formatDate(row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button type="danger" size="mini" @click="delArticle(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 文章详情页的对话框 -->
    <el-dialog
      title="文章预览"
      :visible.sync="detailVisible"
      width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>
      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ formatDate(artDetail.pub_date) }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <img :src="'http://big-event-vue-api-t.itheima.net' + artDetail.cover_img" alt="" />
      <div v-html="artDetail.content"></div>
    </el-dialog>
    <!-- 发布文章的对话框-->
    <el-dialog
      title="发表文章"
      :visible.sync="pubDialogVisible"
      fullscreen
      :before-close="handleClose"
      @closed="closeResetForm"
    >
      <!-- 发布文章的表单区域 -->
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
            <!-- 循环渲染分类的可选项 -->
            <el-option v-for="item in CateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 内容 -->
        <el-form-item label="文章内容" prop="content">
          <!-- 使用v-model 进行数据双向绑定 -->
          <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <!-- 文章封面 -->
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef"
               @click="$refs.iptFile.click()"/>
          <br/>
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none;" accept="image/*" ref="iptFile" @change="onChangeFile"/>
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFile.click()">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pubArticle('已发布')">发布文章</el-button>
          <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
// 导入默认的封面图片
import defaultImg from '@/assets/images/cover.jpg'

export default {
  name: 'ArtList',
  data () {
    return {
      // 保存详情页的数据
      artDetail: {},
      // 控制详情页对话框显示和隐藏
      detailVisible: false,
      // 存储文章总条数
      total: 0,
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      // 控制发布文章对话框的显示和隐藏
      pubDialogVisible: false,
      // 表单的数据对象
      pubForm: {
        title: '',
        cate_id: '',
        // 文章的内容
        content: '',
        // 存储对对象 给null
        cover_img: null,
        state: ''
      },
      // 表单的验证规则对象
      pubFormRules: {
        title: [
          {
            required: true,
            message: '请输入文章标题',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 30,
            message: '文章标题的长度为1-30个字符',
            trigger: 'blur'
          }
        ],
        cate_id: [{
          required: true,
          message: '请选择文章分类',
          trigger: 'change'
        }],
        content: [
          {
            required: true,
            message: '请输入文章内容',
            trigger: 'blur'
          }
        ]
      },
      // 保存文章分类
      CateList: [],
      // 保存文章列表
      ArticleList: []

    }
  },
  created () {
    // 获取文章分类列表
    this.getCateList()
    // 获取文章列表数据
    this.getArticleList()
  },
  methods: {
    // 删除文章
    delArticle(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 确定删除
        const { data: res } = await this.$http.delete('/my/article/info', {
          params: { id }
        })
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)

        if (this.ArticleList.length === 1 && this.q.pagenum > 1) {
          this.q.pagenum--
        }
        // 重新获取数据
        await this.getArticleList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取详情页的数据
    async showDetail(id) {
      const { data: res } = await this.$http.get('/my/article/info', {
        params: { id }
      })
      if (res.code === 0) {
        this.artDetail = res.data
        this.detailVisible = true
      }
    },
    // 重置表单
    resetForm () {
      this.q = {
        pagenum: 1,
        pagesize: 4,
        cate_id: '',
        state: ''
      }
      this.getArticleList()
    },
    // 切换每一页多少条时触发
    handleSizeChange (val) {
      this.q.pagenum = 1
      this.q.pagesize = val
      this.getArticleList()
    },
    // 切换页码值时触发
    handleCurrentChange (val) {
      this.q.pagenum = val
      this.getArticleList()
    },
    // 格式化时间的函数
    formatDate (time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    // 获取文章列表数据
    async getArticleList () {
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      console.log(res)
      if (res.code === 0) {
        this.total = res.total
        this.ArticleList = res.data
      }
    },
    // 重置表单
    closeResetForm () {
      this.$refs.pubFormRef.resetFields()
      this.pubForm.cover_img = null
      this.$refs.imgRef.setAttribute('src', defaultImg)
      this.pubForm.state = ''
    },
    // 发布文章的
    // 1.绑定事件函数
    pubArticle (state) {
      this.pubForm.state = state
      // 2.表单验证
      this.$refs.pubFormRef.validate(async valid => {
        if (!valid) return this.$message.error('文章信息不完整')
        if (this.pubForm.cover_img === null) return this.$message.error('请上传封面')
        const fd = new FormData()
        Object.keys(this.pubForm).forEach(key => {
          // console.log('key:', key)
          // console.log(this.pubForm[key], 'ok')
          fd.append(key, this.pubForm[key])
        })
        // fd.forEach((value, key) => {
        //   console.log(key, '------', value)
        // })
        // 3.发送请求
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 4.关闭对话框
        this.pubDialogVisible = false
        // 清空 input type=file 的值
        this.$refs.iptFile.value = ''

        // 5.重新获取文章列表数据
        await this.getArticleList()
      })
    },
    // 选择图片
    onChangeFile (e) {
      // 获取文件列表
      const files = e.target.files
      if (files.length > 0) {
        // 选择了图片
        console.log(files[0])
        this.pubForm.cover_img = files[0]
        // URL.createObjectURL能够将图片对象 存储到程序的内存中，返回一个图片地址
        const url = URL.createObjectURL(files[0])
        console.log(url)
        // 通过 setAttribute 设置图片的src属性
        this.$refs.imgRef.setAttribute('src', url)
      } else {
        // 没有选中图片 则置空
        this.pubForm.cover_img = null
        this.$refs.imgRef.setAttribute('src', defaultImg)
      }
    },
    // 获取文章分类的数据
    async getCateList () {
      // 发送请求获取数据
      const { data: res } = await this.$http.get('/my/cate/list')
      if (res.code === 0) {
        this.CateList = res.data
      }
    },
    handleClose (done) {
      this.$confirm('此操作将导致数据丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        // done() 可以关闭Dialog
        done()
      }).catch(_ => {
      })
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .btn-pub {
    margin-top: 5px;
  }
}

/deep/ .ql-container {
  min-height: 300px;
}

.el-pagination {
  margin-top: 15px;
}

// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

</style>
